package com.thti.mecool.client.activity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.thti.mecool.client.base.BaseActivity;
import com.thti.mecool.client.base.Cache;
import com.thti.mecool.client.base.HandlerConstant;
import com.thti.mecool.client.model.biz.TaskStepBizImpl;
import com.thti.mecool.client.model.po.TaskManage;
import com.thti.mecool.client.service.LocateService;
import com.thti.mecool.client.util.ImageUtil;

import dalvik.system.VMRuntime;

public class CameraActivity extends BaseActivity implements Callback,
		AutoFocusCallback, OnClickListener {
	private SurfaceView cameraSurfaceView;
	private SurfaceHolder surfaceHolder;
	private ImageButton imageButton;
	private Camera camera1;
	private Bitmap newbm;
	private ImageButton cancel_btn;
	private TaskManage taskManage;
	private String planId, projectId, taskId, stepId;
	private byte[] img;
	private SharedPreferences load;
	private RelativeLayout relativeLayout;
 
	// private SoftReference<Bitmap> sr;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.mecool_camera);
		Intent i = new Intent(this, LocateService.class);
		i.putExtra("flag", 101);
		startService(i);
		load = getSharedPreferences("LocationService", 0);
		VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
		VMRuntime.getRuntime().setMinimumHeapSize(6 * 1024 * 1024);
		relativeLayout = (RelativeLayout) findViewById(R.id.mecool_show_photo_btns);
		Cache.add(this);
		i = getIntent();
		planId = i.getStringExtra("planId");
		projectId = i.getStringExtra("projectId");
		taskId = i.getStringExtra("taskId");
		stepId = i.getStringExtra("StepId");
		taskManage = new TaskManage();
		taskManage.setPlanId(planId);
		taskManage.setProjectId(projectId);
		taskManage.setTaskId(taskId);
		taskManage.setStepId(stepId);
		taskManage.setIsType(1);
		cameraBtnSetting();
	}

	private void cameraBtnSetting() {
		cameraSurfaceView = (SurfaceView) findViewById(R.id.mecool_camera_surfaceview);
		imageButton = (ImageButton) findViewById(R.id.mecool_camera_photoBtn);
		imageButton.setAlpha(0xBB);
		imageButton.setOnClickListener(this);
		setSurface();
		final Animation anim = AnimationUtils
				.loadAnimation(this, R.anim.rotate);
		anim.setFillAfter(true);
		imageButton.setAnimation(anim);
	}

	private void setSurface() {
		surfaceHolder = cameraSurfaceView.getHolder();
		surfaceHolder.addCallback(this);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		setCamera();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		if (camera1 != null)
			camera1.release();
		surfaceHolder.removeCallback(this);
	}

	PictureCallback jpeg = new PictureCallback() {

		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			imageButton.setEnabled(true);
			if (data != null) {
				// 得到新的图片
				newbm = ImageUtil.getThumbnail(data, 600, false);
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				// 将照片转为字节数组
				newbm.compress(Bitmap.CompressFormat.JPEG, 60, baos);
				img = baos.toByteArray();
				// System.out.println(img.length);
				// bm2=BitmapFactory.decodeByteArray(baos.toByteArray(),
				// 0,baos.toByteArray().length);
				// sr=new SoftReference<Bitmap>(bm2);
			}
			if (camera != null) {
				camera1.setPreviewCallback(null);
				camera1.stopPreview();
				camera1.release();
				camera1 = null;
			}
			setContentView(R.layout.mecool_show_photo);
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			ImageView iv = (ImageView) findViewById(R.id.mecool_show_photo_imageview);
			ImageButton save_btn = (ImageButton) findViewById(R.id.mecool_show_photo_save);
			cancel_btn = (ImageButton) findViewById(R.id.mecool_show_photo_cancel);
			iv.setImageBitmap(newbm);
			iv.setOnClickListener(CameraActivity.this);
			Matrix matrix = new Matrix();
			matrix.postRotate(90);
			iv.setImageMatrix(matrix);
			save_btn.setOnClickListener(CameraActivity.this);
			cancel_btn.setOnClickListener(CameraActivity.this);
		}
	};

	@Override
	public void onAutoFocus(boolean success, Camera camera) {
		if (success) {
			camera1.takePicture(null, null, jpeg);
		} else {
			camera1.takePicture(null, null, jpeg);
		}
	}

	private void setCamera() {
		camera1 = Camera.open();
		Parameters parameters = camera1.getParameters();
		List<Camera.Size> jpegize = parameters.getSupportedPictureSizes();
		List<Camera.Size> preview = parameters.getSupportedPreviewSizes();
		for (Camera.Size cs : preview) {
			if (cs.width == getWindowManager().getDefaultDisplay().getWidth()) {
				parameters.setPreviewSize(cs.width, cs.height);
			}
		}
		parameters.setPictureSize(jpegize.get(0).width, jpegize.get(0).height);
		// parameters.setPictureFormat(PixelFormat.JPEG);
		parameters.setJpegQuality(65);
		// parameters.setPreviewFrameRate(5);
		// parameters.setPreviewFormat(PixelFormat.JPEG);
		camera1.setParameters(parameters);
		try {
			camera1.setPreviewDisplay(surfaceHolder);
		} catch (IOException e) {
		}

		camera1.startPreview();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.mecool_show_photo_imageview:
			relativeLayout = (RelativeLayout) findViewById(R.id.mecool_show_photo_btns);
			if (relativeLayout.isShown())
				relativeLayout.setVisibility(8);
			else
				relativeLayout.setVisibility(0);
			break;
		case R.id.mecool_camera_photoBtn:
			camera1.autoFocus(this);
			imageButton.setEnabled(false);
			break;
		case R.id.mecool_show_photo_save:
			if (newbm != null) {
				taskManage.setImages(img);
				TaskStepBizImpl taskStepBizImpl = new TaskStepBizImpl(this);
				taskManage.setLongitude(load.getString("Longitude", null));
				taskManage.setLatitude(load.getString("Latitude", null));
				taskStepBizImpl.updateData(taskManage);
				List<Map<String, Object[]>> list = new ArrayList<Map<String, Object[]>>();
				Map<String, Object[]> map = new HashMap<String, Object[]>();
				String[] ids = new String[] { "1", planId, projectId, stepId,
						taskId };
				map.put(HandlerConstant.PLAN_UPDATE_SQL, ids);
				list.add(map);
				taskStepBizImpl.updateStep(list);
				finish();
			}
			break;
		case R.id.mecool_show_photo_cancel:
			if (newbm != null) {
				if (!newbm.isRecycled())
					newbm.recycle();
				newbm = null;
			}
			setContentView(R.layout.mecool_camera);
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			cameraBtnSetting();
			break;
		}
	}

	@Override
	protected void onDestroy() {
		try {
			if (newbm != null) {
				if (!newbm.isRecycled())
					newbm.recycle();
				newbm = null;
			}
			finalize();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
		imageButton.setEnabled(true);
	}
}
